#!/user/bin/env python
import socket
import sys
import time
import threading
import cPickle as cpickle

#HOST            = sys.arg[0]
#PORT            = sys.arg[1]
MAX_THREADS     = 2 #sys.arg[2]
MAX_LENGTH      = 2**15

class Uac(threading.Thread):
    def __init__(self, (host, port)):
        threading.Thread.__init__(self)
        self.running = False
        self.address = (host, port)
        self.socket  = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect(self.address)
    def run(self):
        self.running = True
        while self.running:
            command = sys.stdin.getline()
            if command == 'invite':
                options = {}
                print 'name: ',
                value = sys.stdin.getline()
                options['name'] = value
                print 'type: ',
                value = sys.stdin.getline()
                options['type'] = value
                self.socket.send('invite(' + cpickle.dumps(options))
                
class uac:
    def __init__(self, host = 'localhost', port = 50055, prot = 'UDP', bufferlen = 1024):
        self.host = host
        self.port = port
        self.prot = prot
        self.bufferlen = bufferlen
        self.sock = None
        try:
            if self.prot == 'UDP':
                self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            elif prot == 'TCP':
                self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.sock.connect((self.host, self.port))
        except socket.error, (value, message):
            print 'erro %d: %s' % (value, message)
            sys.exit(1)

    def __del__(self):
        if self.sock:
            self.sock.close()

    def send(self, data):
        if data and self.sock:
            try:
                if self.prot == 'UDP':
                    self.sock.sendto(data, (self.host, self.port))
                elif self.prot == 'TCP':
                    self.sock.send(data)
                    print self.sock.recv(self.bufferlen)
            except socket.error, (value, message):
                print 'erro %d: %s' % (value, message)
                sys.exit(1)

if __name__ == "__main__":
#    data = {}
#    while True:
#        key = raw_input('Entre com uma chave:')
#        if not key:
#            break
#        value = raw_input('Entre com o valor:')
#        data[key] = value
#    print data

    for i in range(10):
        c = Uac()
        c.send(('test(' + cpickle.dumps([i])))

    
